package ar.activity;

import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import ar.Location.Constant.Define;
import ar.Location.Internet.NetworkStateReceiver;
import ar.Location.Setting.Settings;
import ar.Location.TextToSpeak.TTSHelper;
import ar.activity.R.string;
import ar.globals.Globals;
import ar.gps.GPSListener;
import ar.sensor.SensorListener;
import ar.sql.RouteDatabaseHandler;
import ar.view.adapter.HomeAdapter;

public class HomeActivity extends BaseActivity implements OnInitListener {

	private static final String TAG = "HomeActivity";
	private ImageButton ibMain;
	private GridView gvMain;
	private LocationManager mLocationManager;
	private GPSListener mLocationListener;

	private SensorManager mSensorManager;
	private SensorListener mSensorListener;
	private Sensor orientator;
	private HomeAdapter homeAdapter;
	private AdapterView.OnItemClickListener onItemClick;
	private Bitmap bannerClicked;
	private Bitmap banner;

	NetworkStateReceiver networkReceiver = null;

	Bundle state = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		state = savedInstanceState;

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main1);
		super.onCreate(savedInstanceState);
		tvWhatScreen.setText(res.getString(string.homeScreenName));

		mSensorListener = new SensorListener();
		mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
		// accelerometer = mSensorManager
		// .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		// magnetometer = mSensorManager
		// .getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
		orientator = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

		mLocationListener = new GPSListener();
		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				0, 0, mLocationListener);
		mLocationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
		Globals.connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

		ibMain = (ImageButton) findViewById(R.id.imgMain);
		ibMain.setLayoutParams(new LayoutParams(480, 200));
		ibMain.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ibMain.getBackground().equals(v.getBackground())) {
					if (bannerClicked != null) {
						bannerClicked.recycle();
					}
					bannerClicked = BitmapFactory.decodeResource(res,
							R.drawable.camera_banner_clicked);
					ibMain.setImageBitmap(bannerClicked);
					ibMain.setAdjustViewBounds(true);
					ibMain.setMaxWidth(480);
					ibMain.setMaxHeight(200);
					ibMain.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
				}
				Intent it = new Intent(getApplicationContext(),
						ARCameraActivity.class);
				startActivity(it);
			}
		});

		gvMain = (GridView) findViewById(R.id.gvMain);
		homeAdapter = new HomeAdapter(this);
		gvMain.setAdapter(homeAdapter);
		initItemClickEvent();
		gvMain.setOnItemClickListener(onItemClick);
		initReceiver();

		// Kiem tra khoi tao bien Text To Speak
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, Define.REQ_TTS_STATUS_CHECK);

		// Tao database
		RouteDatabaseHandler myDbHelper = new RouteDatabaseHandler(this);
		try {
			myDbHelper.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}
		myDbHelper.close();
	}

	private void initItemClickEvent() {
		onItemClick = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Intent it = null;
				switch (position) {
				case 0:
					it = new Intent(getApplicationContext(),
							ARMapActivity.class);
					startActivity(it);
					break;
				case 1:
					it = new Intent(getApplicationContext(),
							ShareActivity.class);
					startActivity(it);
					break;
				case 2:
					it = new Intent(getApplicationContext(),
							DataSourceActivity.class);
					startActivity(it);
					break;
				case 3:
					it = new Intent(getApplicationContext(),
							DataFilterActivity.class);
					startActivity(it);
					break;
				case 4:
					it = new Intent(getApplicationContext(),
							SettingsActivity.class);
					startActivity(it);
					break;
				case 5:
					it = new Intent(getApplicationContext(),
							AboutActivity.class);
					startActivity(it);
					break;
				default:
					break;
				}
			}
		};
	}

	private void initReceiver() {
		// TODO Auto-generated method stub
		networkReceiver = new NetworkStateReceiver();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// Stop TTS
		/*
		 * if(TTSHelper.mTts != null) { TTSHelper.mTts.stop(); }
		 */
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(networkReceiver);
		TTSHelper.mTts.shutdown();
	}

	@Override
	protected void onResume() {
		super.onResume();
		ibMain.setBackgroundResource(R.drawable.camera_banner);
		mSensorManager.registerListener(mSensorListener, orientator,
				SensorManager.SENSOR_DELAY_UI);

		registerReceiver(networkReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		mLocationManager.removeUpdates(mLocationListener);
		mSensorManager.unregisterListener(mSensorListener);
		finish();
		Settings.saveSettingLanguage(getApplicationContext());
	}

	@Override
	protected void onUpdateUI() {
		// TODO Auto-generated method stub

		tvWhatScreen.setText(res.getString(string.homeScreenName));
		gvMain = (GridView) findViewById(R.id.gvMain);
		homeAdapter.realeaseBitmap();
		homeAdapter.initBitmap();
		gvMain.setAdapter(homeAdapter);
		gvMain.setOnItemClickListener(onItemClick);

		ibMain = (ImageButton) findViewById(R.id.imgMain);
		if (banner != null) {
			banner.recycle();
		}

		ibMain.setLayoutParams(new LayoutParams(480, 200));
		banner = BitmapFactory.decodeResource(res, R.drawable.camera_banner);
		ibMain.setImageBitmap(banner);
		ibMain.setAdjustViewBounds(true);
		ibMain.setMaxWidth(480);
		ibMain.setMaxHeight(200);
		ibMain.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

		ibMain.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ibMain.getBackground().equals(v.getBackground())) {
					if (bannerClicked != null) {
						bannerClicked.recycle();
					}
					bannerClicked = BitmapFactory.decodeResource(res,
							R.drawable.camera_banner_clicked);
					ibMain.setImageBitmap(bannerClicked);
					ibMain.setAdjustViewBounds(true);
					ibMain.setMaxWidth(480);
					ibMain.setMaxHeight(200);
					ibMain.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
				}
				Intent it = new Intent(getApplicationContext(),
						ARCameraActivity.class);
				startActivity(it);
			}
		});
	}

	// Code xu li phat am thanh
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Define.REQ_TTS_STATUS_CHECK) {
			switch (resultCode) {
			case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
				// TTS is up and running
				TTSHelper.mTts = new TextToSpeech(this, this);
				Log.v(TAG, "Pico is installed okay");
				break;
			case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
			case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
			case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
				// missing data, install it
				Log.v(TAG, "Need language stuff: " + resultCode);
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
				break;
			case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
			default:
				Log.e(TAG, "Got a failure. TTS apparently not available");
			}
		} else {
			// Got something else
		}
	}

	public void onInit(int status) {
		// Now that the TTS engine is ready, we enable the button
		if (status == TextToSpeech.SUCCESS) {
			// speakBtn.setEnabled(true);
			// mTts.setPitch(0.6f);
		}
	}
}